package org.sucri.servlet.handler;

import org.apache.commons.collections15.map.MultiKeyMap;
import org.sucri.dao.NewsEntity;
import org.sucri.floxs.servlet.RequestHandler;
import org.sucri.floxs.servlet.User;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * Created by IntelliJ IDEA.
 * User: Wen Yu
 * Date: Sep 2, 2007
 * Time: 6:15:26 PM
 * To change this template use File | Settings | File Templates.
 */
public class NewsEntryHandler extends RequestHandler$
{
  public NewsEntryHandler(String page)
  {
    super(page, "news_entry");
  }
  public NewsEntryHandler(MultiKeyMap<String, RequestHandler> s)
  {
    super(null, "news_entry", s);
  }

  public boolean processRequest(EntityManagerFactory emf,
                                User user,
                                HttpServletRequest req,
                                HttpServletResponse res) throws ServletException, IOException
  {
    EntityManager em =  null;

    try
    {
      em =  emf.createEntityManager();
      em.getTransaction().begin();

      NewsEntity news = new NewsEntity();

      news.setAuthorUname(req.getParameter("author"));
      news.setContents(req.getParameter("contents"));
      news.setCreateDate(new Timestamp(System.currentTimeMillis()));
      news.setLastmodifyDate(new Timestamp(System.currentTimeMillis()));
      news.setTitle(req.getParameter("title"));

      em.persist(news);
      em.getTransaction().commit();

      res.getOutputStream().println("{success:true}");
    }
    catch (Exception e)
    {
      e.printStackTrace();
      res.getOutputStream().println("{errors: true}");
    }
    finally { em.close(); }

    return true;
  }
}
